import service from "@/path/service"
/**转化处理富文本 */
export function formatRichText(html) {
  if (!(typeof html === "string")) return html
  let newContent = html.replace(/<img[^>]*>/gi, function (match) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}


//函数防抖    不立即执行函数，在规定时间之后执行函数 interval(规定时间)
/**
 * @fn 执行函数
 * @interval  防抖时长
*/
export function debounce(fn, interval) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null
    }, interval)
  }
}


export function getImageSrc(src = "") {
  if (typeof src != "string") return "";
  /**http图片 */
  if (src.indexOf("http") > -1) return src;
  /**base64图片 */
  if (src.indexOf("base64") > -1) return src;
  /**未拼接http的 http图片 */
  if ((src.indexOf(".gif") > 0) || (src.indexOf(".png") > 0) || (src.indexOf(".jpg") > 0) || (src.indexOf(".jpeg") > 0)) {
    return src ? `${service.imageUrl}${src}` : "";
  }
  return finishBase64(src)
}

const subscribeMessageed = { value: false }
/**发送模板消息 */
export function subscribeMessage(id = "qkxa5Z1M2nGGNi_6BLxh7o585phOkKtHUuvzHHjHkA8") {
  return new Promise((resolve, reject) => {
    if (subscribeMessageed.value === true) return reject()
    subscribeMessageed.value = true
    uni.showModal({
      title: "温馨提示",
      content: "是否同意接收服务消息？",
      success(res) {
        if (res.confirm) {
          uni.requestSubscribeMessage({
            tmplIds: [id],
            success(res) {
              if (res[id]) {
                resolve(res[id])
              } else {
                reject()
              }
            },
            fail() {
              reject()
            }
          })
        } else {
          reject()
        }
      },
      fail() {
        reject()
      }
    })
  })
}



/**
 * 是否对象
*/
export const isObj = (o) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Object'
}

/**
 * 是否JSON字符串
*/
export function isJsonStr(str) {
  try {
    if (typeof JSON.parse(str) == "object") {
      return true;
    }
  } catch (e) {
  }
  return false;
}